package cn.itcast.java.jdbc;

import java.sql.*;

/**
 * Author itcast
 * Date 2021/10/14 10:18
 * Desc TODO
 */
public class JDBCUtils {
    private static Statement statement = null;
    private static ResultSet rs = null;
    private static Connection conn = null;
    static String url = "jdbc:mysql://192.168.88.163:3306/day06?useSSL=false";
    static String user = "root";
    static String password="123456";

    //装载驱动，使用静态代码块
    //在类加载而加载，在构造器之前加载。语法: static {}
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个数据库的连接对象
     * @return
     */
    public static Connection getConn(){

        try {
            conn = DriverManager.getConnection(
                    url,
                    user,
                    password
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库连接的资源
     */
    public static void close(){
        try{
            if(rs!=null) rs.close();
            if(statement!=null) statement.close();
            if(conn!=null &&!conn.isClosed()) conn.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
